package com.leslie.springboottest.controller;

import com.leslie.springboottest.data.Person;
import com.leslie.springboottest.data.PersonResponse;
import com.leslie.springboottest.enums.PersonResponseEnum;
import com.leslie.springboottest.excption.PersonException;
import com.leslie.springboottest.repository.PersonRepository;
import com.leslie.springboottest.service.PersonService;
import com.leslie.springboottest.util.PersonResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
public class PersonController {
    @Autowired
    private PersonRepository personRepository;
    @Autowired
    private PersonService personService;

    @GetMapping("/person")
    public PersonResponse queryPersons(){
        return PersonResponseUtil.success(personRepository.findAll());
    }

    @PostMapping("/person")
    public PersonResponse createPerson(@Valid Person person, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            PersonResponseUtil.error(PersonResponseEnum.DATA_ERR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        return PersonResponseUtil.success(personRepository.save(person));
    }

    @GetMapping("/person/{id}")
    public PersonResponse findPerson(@PathVariable("id") Integer id){
        return PersonResponseUtil.success(personRepository.findById(id).orElse(null));
    }

    @PutMapping("/person/{id}")
    public PersonResponse updatePerson(@PathVariable("id") Integer id,
                               @Valid Person person, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return PersonResponseUtil.error(PersonResponseEnum.DATA_ERR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        person.setId(id);
        return PersonResponseUtil.success(personRepository.save(person));
    }

    @DeleteMapping("/person/{id}")
    public void deletePerson(@PathVariable("id") Integer id){
        personRepository.deleteById(id);
    }

    @GetMapping("/person/getAge/{age}")
    public void getAge(@PathVariable("age") Integer age) throws PersonException {
        personService.getAge(age);
    }
}